<?php $this->load->view('common/default_header.php');?>

<!-- <div class="banner"><img src="<?php echo img_url("/wcp/banner.jpg");?>" width="100%"></div> -->
<div class="banner btn-success">
<!-- <a  class="banner btn-success" href="http://qm.qq.com/cgi-bin/qm/qr?k=VXBvb4w-zdsAH-6dHgcYw9leWHkS-2Te&auth=7bfa4f6968ecdcd6a0d8e80cf90ed2e082011423802838c3d0d1e88bbe62dbbf0fd3e849400a5d1f">点击加入官方服务QQ群:144950915</a> -->
<!-- <a  class="banner btn-success" href="https://img.720quan.com/huodong/html/index.html">微盘大师赛正在进行中点击获取详情</a> -->
<a  class="banner btn-success" href="https://720quan.com/about/intro">微盘大师赛已结束点击获取详情</a>
</div>
<div class="header">
    <div class="btnbox">
        <a href="/cny/deposit" class="btn btn-warning btn-lg" style="border-radius:0px;">充值</a>
    </div>
    <div class="l">
      <a href="/user">
        <h4>我的账户(元)</h4>
        <h2><font class="cny"><?php echo (!empty($user_info['cny']))?$user_info['cny']:'0.00';?></font></h2>
      </a>
    </div>
    <div class="r">
		<a href="/ticket">
        <h4>体验券</h4>
        <h2><font class="ticket"><?php echo (!empty($user_info['ticket']))?$user_info['ticket']:0;?></font></h2>
		</a>
    </div>
    <div class="btnbox">
        <a href="/cny/deposit" class="btn btn-warning btn-lg"><?php echo ($test==1)?"测试":"充值";?></a>
    </div>
    <div class="clear"></div>
</div>
<div class="weui_tab">
        <div class="weui_navbar">
            <?php
            if(!empty($productArr)) foreach($productArr as $stype=>$productType){
              foreach($productType as $name=>$product){
                $style = '';
                if($name=='XINA50') $style='weui_bar_item_on';
                if($name=='UK100') $style='weui_bar_item_on';
            ?>
            <div class="weui_navbar_item <?php echo $style;?>" type-data="<?php echo $name;?>">
                <?php echo $product['desc'];?>
            </div>
            <?php
              }
            }
            ?>
            <div class="clear"></div>
        </div>
        <!-- <div class="line"></div> -->
        <?php
        if(!empty($productArr)) foreach($productArr as $stype=>$productType){
          foreach($productType as $name=>$product){
            $style = 'hides';
            if($name=='XINA50') $style='';
            if($name=='UK100') $style='';
        ?>
        <div class="weui_tab_bd <?php echo $style;?>">
           <div class="m15">
              <div class="dt">
                   <h1>
                      <b id="<?php echo $name;?>_LAST_PRICE">--</b>
                      <i>
                        <font id="<?php echo $name;?>_UPARR">&uarr;</font>
                        <span id="<?php echo $name;?>_UD">--</span>
                        <span id="<?php echo $name;?>_RANGE" style="margin-left:5px;">--</span>
                      </i>
                       <p>
                          <span>昨收：<font id="<?php echo $name;?>_CLOSE_PRICE">--</font></span>
                          <span>最高: <font id="<?php echo $name;?>_HIGH">--</font></span>
                       <p>
                          <span>今开：<font id="<?php echo $name;?>_OPEN_TICK">--</font></span>
                          <span>最低: <font id="<?php echo $name;?>_LOW">--</font></span>
                       </p>
                   </h1>
                   <h2 class="zd">
                      <input type="hidden" name="<?php echo $name;?>_ask_com" id="<?php echo $name;?>_ask_com">
                      <input type="hidden" name="<?php echo $name;?>_bid_com" id="<?php echo $name;?>_bid_com">
                      <a class="mz" href="javascript:marketOpen(<?php echo $product['pid'];?>,'bid')">买涨</a>
                      <a class="md" href="javascript:marketOpen(<?php echo $product['pid'];?>,'ask')">买跌</a>

                   </h2>
              </div>
              <div class="cc" id="<?php echo $name;?>_position">
              <?php if(!empty($positionArr[$name])){?>
                   <h1>
                      <a data-toggle="collapse" href="#collapse<?php echo $name;?>"><span>持仓</span><span id="<?php echo $name;?>_direction"><font class="<?php echo ($ykArr[$name]['net']>0)?'red':'green';?>"><?php if($ykArr[$name]['net']!=0){echo $ykArr[$name]['direction'];}else{echo "&nbsp;";}?></font></span><span id="<?php echo $name;?>_net"><?php if($ykArr[$name]['net']!=0){echo abs($ykArr[$name]['net'])."手";}else{echo "&nbsp;";}?></span><span id="<?php echo $name;?>_zyk"><font class="<?php echo ($ykArr[$name]['zyk']>0)?'red':'green';?>"><?php if($ykArr[$name]['zyk']>0){echo "+";};?><?php echo $ykArr[$name]['zyk'];?></font></span><span class="selt"><?php echo $product['settlement'];?>结算<i></i></span><div class="clear"></div></a>
                   </h1>
                   <div id="collapse<?php echo $name;?>" class="collapsein">
                      <?php foreach($positionArr[$name] as $posData){?>
                      <h2 id="<?php echo $name.'_'.$posData['id'];?>" class="<?php echo $name.'_pos';?>">
                        <span><?php echo $product['desc'];?></span>
                        <span><?php echo $posData['price'];?><?php echo ($posData['bs']=='bid')?"<i class='red'>↑</i>":"<i class='green'>↓</i>";?></span>
                        <span><?php echo $posData['num'];?><?php echo ($posData['dtype']=='ticket')?'张':'手';?></span>
                        <span><font class="<?php echo ($posData['yk']>0)?'red':'green';?>"><?php echo $posData['yk'];?></font></span>
                        <span><a href="javascript:marketClose('<?php echo $name;?>','<?php echo $posData['dtype'];?>','<?php echo $posData['bs'];?>_ping',<?php echo $product['pid'];?>,<?php echo $posData['id'];?>)" class="btn btn-warning btn-sm">平仓</a></span>
                        <div class="clear"></div>
                      </h2>
                      <?php }?>
                   </div>
              <?php }?>
              </div>
              <!-- <div style="text-align: center;" class="<?php echo $name;?>_highChart">加载中...</div> -->

           </div>
        </div>
        <?php
          }
        }
        ?>
    </div>
    <div style="text-align: center;height:300px;-webkit-box-shadow: 0 1px 1px rgba(0,0,0,0.1);" id="EChart">加载中...</div>
<?php //$this->load->view('common/rank.php');?>
<div class="clear"></div>
<div class="weui_tab  tab1">
        <div class="weui_navbarr">
            <div class="weui_navbar_item1 weui_bar_item_on new_navbar">
                实时资讯
            </div>
            <div class="weui_navbar_item1 new_navbar">
                系统公告
            </div>
        </div>
        <div class="clear"></div>
        <div class="weui_tab_bd1 new_tab_bd">
            <div class="news_box" id="information">

            </div>
        </div>

        <div class="weui_tab_bd1 new_tab_bd hides">
            <div class="news_box">
                    <div class="weui_media_box weui_media_text">
                        <a href="#gonggao2" data-toggle="collapse">
                          <h4 class="weui_media_title">要点啥微盘隆重上线，10元交易体验券送不停</h4>
                          <p class="time">2016-06-07 12:00:00</p>
                          <span class="r_ico"></span>
                        </a>
                        <div class="collapse" id="gonggao2" >
                          <p>
                            由要点啥开发并提供技术支持的要点啥微盘已结束测试，正式对外开放。要点啥微盘提供新华A50指数、道琼斯指数、原油和黄金四种国际主流交易品种，保证金只需10元，交易简便易上手，微信端实时把握行情，为用户提供全新的交易体验。<br>
                            即日起，凡关注微信公众号“要点啥微盘”的用户每日可获得10元免费体验券一张，体验券可用于交易所有合约产品，盈利可直接提现，亏的算我们的，赚的是用户的。<br>
                            同时，为让更多人体验微操盘的交易乐趣，要点啥同步推出微操盘经纪人计划，凡推荐好友关注要点啥微盘可获得其交易额1%的佣金分成，约合每手0.1元。<br>
                            要点啥微盘提供了极低风险的操盘实战机会，只需10元即可交易。为交易者深化对国际主流金融品种的认识，熟悉基本的交易知识和交易规则，引导交易者认识自身风险承受能力和培养交易者的风控意识提供了良好的机会！<br>
                            要点啥微盘诚邀您来体验！<br>
                          </p>
                        </div>
                    </div>

                    <div class="weui_media_box weui_media_text">
                      <a href="#gonggao1" data-toggle="collapse">
                        <h4 class="weui_media_title">要点啥微盘删档公测中</h4>
                        <p class="time">2016-06-01 12:40</p>
                        <span class="r_ico"></span>
                      </a>
                    </div>
                </div>
        </div>

    </div>


<script src="<?php echo js_url("/wcp/jquery-1.9.1.min.js"); ?>?20160329001" type="text/javascript"></script>
<script src="<?php echo js_url("/wcp/bootstrap.min.js"); ?>?20160329001" type="text/javascript"></script>
<script src="<?php echo js_url("/wcp/socket.io.js"); ?>?20160329001" type="text/javascript"></script>
<script src="<?php echo js_url("/wcp/main.js"); ?>?20160329001" type="text/javascript"></script>
<script src="<?php echo js_url("/wcp/highcharts.js"); ?>?20160329001" type="text/javascript"></script>
<script src="<?php echo js_url("/wcp/jquery.timers.js"); ?>?20160329001" type="text/javascript"></script>
<script src="<?php echo js_url("/wcp/bootstrap-dialog.min.js"); ?>?20160329001" type="text/javascript"></script>
<script src="<?php echo js_url("/wcp/jquery.blockUI.js"); ?>?20160329001" type="text/javascript"></script>

<script src="<?php echo js_url("/wcp/echarts.min.js"); ?>?20160329001" type="text/javascript"></script>
<script src="<?php echo js_url("/wcp/shine.js"); ?>?20160329001" type="text/javascript"></script>
<script>

var regHtml = '<form method="post" accept-charset="utf-8" id="regForm" onsubmit="return false;">';
regHtml += '<div class="form-group"><input type="text" name="phone" class="form-control" id="phone" placeholder="手机号码"></div>';
regHtml += '<div class="form-group"><input type="password" name="password" class="form-control" id="password" placeholder="交易密码，4-18位字符"></div>';
regHtml += '<div class="form-group"><input type="password" name="password2" class="form-control" id="password2" placeholder="确认交易密码"></div>';
//regHtml += '<div class="form-group"><div class="col-md-6" style="padding-left:0"><input type="text" name="captcha" class="form-control" id="captcha" placeholder="图片验证码"></div><div class="col-md-6" style="padding-left:0"><img src="/user/captcha" alt="验证码" id="captcha_code" class="captcha_img" /><a href="javascript:changeCaptchaCode();">换一张</a> </div> </div>';
regHtml += '<div class="form-group"><label><a href="javascript:getSMSCode()" id="getSMSBtn" class="btn btn-warning">获取验证码</a></label></div>';
regHtml += '<div class="form-group"><input type="text" name="vaildCode" class="form-control" id="vaildCode" placeholder="短信验证码"></div>';
regHtml += '<input type="hidden" name="redirect" id="redirect" value="<?php echo $redirect;?>"><a href="javascript:reg()" class="btn btn-block btn-warning">确认</a>';
regHtml += '</form>';
//regHtml += '<script>function changeCaptchaCode(){$("#captcha_code").attr("src","/user/captcha?r=" + Math.random());}<\/script>';


var loginHtml = '<form method="post" accept-charset="utf-8" id="loginForm" onsubmit="return false;">';
loginHtml += '<div class="form-group">';
loginHtml += '<input type="password" name="password" class="form-control" id="password" placeholder="交易密码">';
loginHtml += '</div>';
loginHtml += '<div class="checkbox"><label>';
loginHtml += '<input type="checkbox" name="isFree" class="label-control" id="isFree" value="1">免密码登陆';
loginHtml += '</label></div>';
loginHtml += '<a href="javascript:login()" class="btn btn-block btn-warning">确认</a>';
loginHtml += '<div class="form-group text-center" style="margin-top:15px">';
loginHtml += '<label><a href="javascript:forgotPwd();">忘记交易密码？</a></label>';
loginHtml += '<input type="hidden" name="redirect" id="redirect" value="<?php echo $redirect;?>"></div>';
loginHtml += '</form>';


var forgotHtml = '<form method="post" accept-charset="utf-8" id="forgotForm" onsubmit="return false;">';
forgotHtml += '<div class="form-group"><label>已绑定手机号码：<?php if(isset($userData["phone"])){echo $userData["phone"];}?></label></div>';
//forgotHtml += '<div class="form-group"><div class="col-md-6" style="padding-left:0"><input type="text" name="captcha" class="form-control" id="captcha" placeholder="图片验证码"></div><div class="col-md-6" style="padding-left:0"><img src="/user/captcha" alt="验证码" id="captcha_code" class="captcha_img" /><a href="javascript:changeCaptchaCode();">换一张</a> </div> </div>';
forgotHtml += '<div class="form-group"><label><a href="javascript:getSMSCodeByUid(<?php if(isset($userData["uid"])){echo $userData["uid"];}?>)" id="getSMSBtn" class="btn btn-warning">获取验证码</a></label></div>';
forgotHtml += '<div class="form-group"><input type="text" name="vaildCode" class="form-control" id="vaildCode" placeholder="短信验证码"></div>';
forgotHtml += '<div class="form-group"><input type="password" name="password" class="form-control" id="password" placeholder="输入新的交易密码，4-18位字符"></div>';
forgotHtml += '<input type="hidden" name="uid" value="<?php if(isset($userData["uid"])){echo $userData["uid"];}?>"><a href="javascript:forgot()" class="btn btn-block btn-warning">确认</a>';
forgotHtml += '<div class="form-group text-center" style="margin-top:15px"><label><a href="javascript:loginModal();">马上登陆</a></label></div>';
forgotHtml += '</form>';
//forgotHtml += '<script>function changeCaptchaCode(){$("#captcha_code").attr("src","/user/captcha?r=" + Math.random());}<\/script>';

$(function(){
  $(".weui_navbar_item").click(function(){
    var typeData = $(this).attr('type-data');
    $(".weui_navbar_item").eq($(this).index()).addClass('weui_bar_item_on').siblings('.weui_bar_item_on').removeClass('weui_bar_item_on');
    $(".weui_tab_bd").hide().eq($(this).index()).show();
    $('body').stopTime('XINA50_position');
    $('body').stopTime('DAOUSD_position');
    $('body').stopTime('XTIUSD_position');
    $('body').stopTime('XAUUSD_position');
    show_chart(typeData);
    $('body').everyTime('5s',typeData+'_position',function(){
        getPosition(typeData);
    });
  });
  $(".new_navbar").click(function(){
    $(".new_navbar").eq($(this).index()).addClass('weui_bar_item_on').siblings('.weui_bar_item_on').removeClass('weui_bar_item_on');
    $(".new_tab_bd").hide().eq($(this).index()).show();
  });

	 $(".rank_navbar").click(function(){
	 	$(".rank_navbar").eq($(this).index()).addClass('weui_bar_item_on').siblings('.weui_bar_item_on').removeClass('weui_bar_item_on');
	 	$(".rank_tab_bd").hide().eq($(this).index()).show();
	 });

  <?php if($reg==1){?>
    BootstrapDialog.show({
          title: '用户注册',
          closable:false,
          type: BootstrapDialog.TYPE_DEFAULT,
          message: regHtml
      });
  <?php }else{?>
    <?php if(empty($user_info)){?>
      window.loginDialog = new BootstrapDialog({
          title: '输入交易密码',
          closable:false,
          type: BootstrapDialog.TYPE_DEFAULT,
          message: loginHtml
      });
      window.loginDialog.open();
    <?php }?>
  <?php }?>

  $('body').everyTime('5s',function(){
    $.ajax({
        type: 'GET',
        url: "/ajax/userInfo",
        dataType: 'json',
        success: function(data){
          if(data.logined==0 && $(".header .blockUI").length <= 0){
            $('.header').block({ message: "<botton class='btn btn-warning' onclick='wx.closeWindow();'>登陆超时，请重新进入</botton>" });
          }
          $('.cny').html(data.cny);
          $('.ticket').html(data.ticket);
        }
    });
  });

  $('body').everyTime('5s','XINA50_position',function(){
      getPosition('XINA50');
  });

  $.get("/ajax/information", function(result){
      $("#information").html(result);
  });

   // $.get("/ajax/rank", function(result){
   //     $("#rankList").html(result);
   // });

});

function loginModal(){
  window.loginDialog.setTitle('输入交易密码');
  window.loginDialog.setMessage(loginHtml);
  window.loginDialog.open();
}

function forgotPwd(){
  window.loginDialog.setTitle('找回密码');
  window.loginDialog.setMessage(forgotHtml);
  window.loginDialog.open();
}


function login(){
  var passwd = $('#loginForm #password').val();
  if(passwd==''){
    myAlert("请输入交易密码");
    return;
  }
	$.ajax({
	   	type: "POST",
	   	url: "/api/user/login",
	   	dataType: 'json',
	   	data: $("#loginForm").serialize(),
	   	success: function(data){
	     	if(data.code==0){
	     		location.href=data.redirect;
	     	}else{
	     		myAlert(data.message);
	     	}
	    },
	    error: function(XHR,textStatus,errorThrown) {
            myAlert("无效请求");
        }
	});
}
//倒计时操作
function countDown($button, time) {
    if (time > 0) {
        $button.addClass('disabled');
        $button.text("重新发送("+time+")");
        setTimeout(function () {
            countDown($button, --time);
        }, 1000);
    } else {
        $button.removeClass('disabled');
        $button.text("获取验证码");
    }
}


function getSMSCode(){
  // var captcha = $.trim($('#captcha').val());
  // if(captcha==''){
  //   myAlert("图片验证码错误！");
  //     return;
  // }
  var phone = $.trim($('#phone').val());
  var phoneReg = /^1[0-9]{10}$/;
  if (!phoneReg.test(phone)) {
      myAlert("手机号码输入有误！");
      return;
  }
  var disabled = $("#getSMSBtn").hasClass('disabled');
  if(disabled==undefined||disabled==false){
    $.ajax({
        type: 'POST',
        url: "/ajax/getSMSCode",
        dataType: 'json',
        data: {'type':'reg','area':86,'phone':phone} ,
        success: function(data){
          if(data.errno==0 || data.errno==1){
            countDown($('#getSMSBtn'),data.data.expire);
          }else{
            myAlert(data.msg);
          }
        }
    });
  }else{
    return;
  }
}


function getSMSCodeByUid(uid){
  // var captcha = $.trim($('#captcha').val());
  // if(captcha==''){
  //   myAlert("图片验证码错误！");
  //     return;
  // }
  var disabled = $("#getSMSBtn").hasClass('disabled');
  if(disabled==undefined||disabled==false){
    $.ajax({
        type: 'POST',
        url: "/ajax/getSMSCode",
        dataType: 'json',
        data: {'type':'forgot','uid':uid} ,
        success: function(data){
          if(data.errno==0 || data.errno==1){
            countDown($('#getSMSBtn'),data.data.expire);
          }else{
            myAlert(data.msg);
          }
        }
    });
  }else{
    return;
  }
}

function forgot(){
  var vaildCode = $('#forgotForm #vaildCode').val();
  if(vaildCode==''){ myAlert("请输入手机验证码");return;}
  var password = $('#forgotForm #password').val();
  if(password==''){ myAlert("请输入新交易密码");return;}
  $.ajax({
      type: "POST",
      url: "/api/user/forgot",
      dataType: 'json',
      data: $("#forgotForm").serialize(),
      success: function(data){
        if(data.code==0){
          location.href=data.redirect;
        }else{
          myAlert(data.message);
        }
      },
      error: function(XHR,textStatus,errorThrown) {
            myAlert("无效请求");
        }
  });
}

function reg(){
  var phone = $('#regForm #phone').val();
  if(phone=='') {myAlert("请输入手机号码");return;}
  var password = $('#regForm #password').val();
  if(password=='') {myAlert("请输入交易密码");return;}
  var password2 = $('#regForm #password2').val();
  if(password2=='') {myAlert("请输入确认交易密码");return;}
  var vaildCode = $('#regForm #vaildCode').val();
  if(vaildCode=='') {myAlert("请输入手机验证码");return;}
  $.ajax({
      type: "POST",
      url: "/api/user/register",
      dataType: 'json',
      data: $("#regForm").serialize(),
      success: function(data){
        if(data.code==0){
          location.href=data.redirect;
        }else{
          myAlert(data.message);
        }
      },
      error: function(XHR,textStatus,errorThrown) {
            myAlert("无效请求");
        }
  });
}

var marketOpenDialog = {};
//市价开仓
function marketOpen(pid, action){
  marketOpenDialog = new BootstrapDialog({
    title: '确认购买',
    closeByBackdrop: false,
    closeByKeyboard: false,
    type: BootstrapDialog.TYPE_DEFAULT,
    message: function(dialog) {
        var $message = $('<div></div>');
        var pageToLoad = dialog.getData('pageToLoad');
        $message.load(pageToLoad);
        return $message;
    },
    data: {
        'pageToLoad': '/api/cfd/ajaxTrade?pid='+pid+'&action='+action
    }
  });
  marketOpenDialog.open();
}

function marketOpenHandel(name,action,pid){
  var dtype = $("#openTrade input[name='dtype']:checked").val();
  var com = $('#'+name+'_'+action+'_com').val();
  var num = $('#marketOpenNum').val();
  $.ajax({
    type: "POST",
    url: "/api/cfd/trade",
    dataType: 'json',
    data: {pid:pid,action:action,'dtype':dtype,'com':com,'num':num},
    success: function(data){
      if(data.code==0){
        marketOpenDialog.close();
      }else{
        marketOpenDialog.setTitle('错误提示');
        marketOpenDialog.setMessage(data.message);
        marketOpenDialog.setButtons([{label: '关闭',action: function(dialog){dialog.close();}}]);
        marketOpenDialog.open();
      }
    },
    error: function(XHR,textStatus,errorThrown) {
      marketOpenDialog.setTitle('错误提示');
      marketOpenDialog.setMessage("请求无效");
      marketOpenDialog.open();
    }
  });
}

var marketCloseDialog = new BootstrapDialog({
    closeByBackdrop: false,
    closeByKeyboard: false,
    type: BootstrapDialog.TYPE_DEFAULT
});

//市价平仓
function marketClose(name,dtype,action,pid,posid){
  // BootstrapDialog.confirm({
  //   title: '确认平仓',
  //   message: '你确定平仓吗?',
  //   closeByBackdrop: false,
  //   closeByKeyboard: false,
  //   type: BootstrapDialog.TYPE_DEFAULT,
  //   btnCancelLabel: '取消',
  //   btnOKLabel: '平仓',
  //   btnOKClass: 'btn-warning',
  //   callback: function(result){
  //     if(result) {
        var com = $('#'+name+'_'+action+'_com').val();
        $.ajax({
            type: "POST",
            url: "/api/cfd/trade",
            dataType: 'json',
            data: {pid:pid,action:action,'dtype':dtype,'com':com,'posid':posid},
            success: function(data){
              if(data.code!=0){
                // marketCloseDialog.setTitle('错误提示');
                // marketCloseDialog.setMessage(data.message);
                // marketCloseDialog.setButtons([{label: '关闭',action: function(dialog){dialog.close();}}]);
                // marketCloseDialog.open();
              }
            },
            error: function(XHR,textStatus,errorThrown) {
                  myAlert("无效请求");
              }
        });
  //     }
  //   }
  // });
}

function getPosition(name){
  $.ajax({
      type: 'GET',
      url: "/api/cfd/ajax",
      dataType: 'json',
      data:{'name':name,'action':'position'},
      success: function(data){
        var html = "";
        var style1 = (data.zyk>0)?"red":"green";
        var style2 = '';
        var updown = '';
        var posArr = [];//当前持仓的ids
        if(data.code==0){
          if(data.isEmpty==0){
              var zyxFH = (data.zyk>0)?"+":"";
              var netClass = (data.net>0)?"red":"green";
              var netNum="&nbsp;";
              if(data.net!=0){
                netNum = Math.abs(data.net)+"手";
              }
              if($.trim($("#"+data.name+"_position").html()) == ""){
                $("#"+data.name+"_position").html('<h1><a data-toggle="collapse" href="#collapse'+data.name+'"><span>持仓</span><span id="'+data.name+'_direction"><font class="'+netClass+'">'+((data.net!=0)?data.direction:"&nbsp;")+'</font></span><span id="'+data.name+'_net">'+netNum+'</span><span id="'+data.name+'_zyk"><font class="'+style1+'">'+zyxFH+data.zyk+'</font></span><span class="selt">'+data.settlement+'结算<i></i></span><div class="clear"></div></a></h1><div id="collapse'+data.name+'" class="collapse"></div>');
              }
              $("#"+data.name+"_direction").html('<font class="'+netClass+'">'+((data.net!=0)?data.direction:"&nbsp;")+'</font>');
              $("#"+data.name+"_net").html(netNum);
              $("#"+data.name+"_zyk").html('<font class="'+style1+'">'+zyxFH+data.zyk+'</font>');
              $.each(data.data,function(i,pos){
                var unit = (pos.dtype=='ticket')?'张':'手';
                style2 = (pos.yk>0)?'red':'green';
                updown = (pos.bs=='bid')?'<i class="red">↑</i>':'<i class="green">↓</i>';
                if($("#"+data.name+"_"+pos.id).length> 0){
                    $("#"+data.name+"_"+pos.id+" span:nth-child(2)").html(pos.price+updown);
                    $("#"+data.name+"_"+pos.id+" span:nth-child(3)").html(pos.num+unit);
                    $("#"+data.name+"_"+pos.id+" span:nth-child(4)").html('<font class="'+style2+'">'+pos.yk+'</font>');
                }else{
                    html += '<h2 id="'+data.name+'_'+pos.id+'" class="'+data.name+'_pos">';
                    html += '<span>'+data.desc+'</span><span>'+pos.price+updown+'</span><span>'+pos.num+unit+'</span><span><font class="'+style2+'">'+pos.yk+'</font></span><span><a href="javascript:marketClose(\''+data.name+'\',\''+pos.dtype+'\',\''+pos.bs+'_ping\','+data.pid+','+pos.id+')" class="btn btn-warning btn-sm">平仓</a></span><div class="clear"></div></h2>';
                    html += '</h2>';
                }
                posArr.push(data.name+"_"+pos.id);
              });
              if(html!='') $("#collapse"+data.name).prepend(html);
              $.each($('.'+data.name+'_pos'), function(i, item){
                 var id = $(item).attr('id');
                 if($.inArray(id,posArr)<0){
                    $(item).remove();
                 }
              });
          }else{
            $("#"+data.name+"_position").html('');
          }
        }
      }
  });
}

var tmpData = {};
var socket = io.connect('<?php echo $socket_url;?>',{'max reconnection attempts':'Infinity','reconnectiondelay':5,'reconnection limit':3000});
socket.on('connect', function() {
  <?php
  if(!empty($productArr)) foreach($productArr as $productType){
    foreach($productType as $name=>$product){
      $tradeKey = $name.'_TRADE';
  ?>
  socket.on('<?php echo $tradeKey?>', function(data) {
    // console.log(data);
    var UD = accSub(data.LAST_PRICE, data.CLOSE_PRICE);
    var RANGE = Math.round(accMul(accDiv(UD, data.CLOSE_PRICE),'100')*100)/100;
    $("#<?php echo $name;?>_LAST_PRICE").html(data.LAST_PRICE);
    $("#<?php echo $name;?>_LAST_PRICE2").html(data.LAST_PRICE);
    $("#<?php echo $name;?>_BID_PRICE").html(data.BID_PRICE);
    $("#<?php echo $name;?>_ASK_PRICE").html(data.ASK_PRICE);
    $("#<?php echo $name;?>_CLOSE_PRICE").html(data.CLOSE_PRICE);
    if(data.OPEN_TICK == undefined){
      $("#<?php echo $name;?>_OPEN_TICK").html(data.CLOSE_PRICE);
    }else{
      $("#<?php echo $name;?>_OPEN_TICK").html(data.OPEN_TICK);
    }
    $("#<?php echo $name;?>_HIGH").html(data.HIGH);
    $("#<?php echo $name;?>_LOW").html(data.LOW);
    $("#<?php echo $name;?>_UD").html(UD);
    $("#<?php echo $name;?>_RANGE").html(RANGE+"%");

    $("#<?php echo $name;?>_ask_com").val(data.WCP_ASK_COM);
    $("#<?php echo $name;?>_bid_com").val(data.WCP_BID_COM);

    $(".<?php echo $name;?>_ask_com").html(data.WCP_ASK_COM);
    $(".<?php echo $name;?>_bid_com").html(data.WCP_BID_COM);
    $(".<?php echo $name;?>_BID_PRICE").html(data.BID_PRICE);
    $(".<?php echo $name;?>_ASK_PRICE").html(data.ASK_PRICE);
    if(UD<0){
      $("#<?php echo $name;?>_UPARR").html('↓');
      $("#<?php echo $name;?>_UPARR2").html('↓');
      $("#<?php echo $name;?>_UPARR").removeClass().addClass("green");
      $("#<?php echo $name;?>_LAST_PRICE").removeClass().addClass("green");
      $("#<?php echo $name;?>_LAST_PRICE_SHOW").removeClass().addClass("green");
      $("#<?php echo $name;?>_UD").removeClass().addClass("green");
      $("#<?php echo $name;?>_RANGE").removeClass().addClass("green");
    }else{
      $("#<?php echo $name;?>_UPARR").html('↑');
      $("#<?php echo $name;?>_UPARR2").html('↑');
      $("#<?php echo $name;?>_UPARR").removeClass().addClass("red");
      $("#<?php echo $name;?>_LAST_PRICE").removeClass().addClass("red");
      $("#<?php echo $name;?>_LAST_PRICE_SHOW").removeClass().addClass("red");
      $("#<?php echo $name;?>_UD").removeClass().addClass("red");
      $("#<?php echo $name;?>_RANGE").removeClass().addClass("red");
    }
    tmpData['<?php echo $tradeKey?>'] = data;
  });
  <?php }}?>
  socket.on('disconnect', function(data) {

  });
  socket.on('error', function(data) {
    return;
  });
});


var global_type = 'XINA50';
function show_chart(type){
  global_type = type;
  $.ajax({
    timeout: 10000,
    url: '/ajax/getKlineData2',
    // dataType: 'json',
    type: 'GET',
    data: {type: type},
    success: function(msg) {
      var msg = eval('('+msg+')');
      var data = splitData(msg);
      drawKline(data,'XINA50');
    }
  });
}
var myChart = echarts.init(document.getElementById('EChart'),'shine');

$(function(){
  $.ajax({
    timeout: 10000,
    url: '/ajax/getKlineData2',
    // dataType: 'json',
    type: 'GET',
    data: {type: 'XINA50'},
    success: function(msg) {
      var msg = eval('('+msg+')');
      var data = splitData(msg);
      drawKline(data,'XINA50');
    }
  });

});


function drawKline(data,symbol){
  var option = {
      title: {
          text: symbol,
          left: 0
      },
      tooltip: {
          trigger: 'axis',
          axisPointer: {
              type: 'line'
          }
      },
      legend: {
          data: ['分时图', '1分钟K线图'],
          selected:{
              '分时图':false,
              '1分钟K线图':true
          }
      },
      grid: {
          top: '10%',
          left: '2%',
          right: '5%',
          bottom: '1%',
          containLabel: true
      },
      xAxis: {
          type: 'category',
          data: data.categoryData,
          scale: true,
          boundaryGap : false,
          axisLine: {onZero: false},
          splitLine: {show: false},
          splitNumber: 20,
          min: 'dataMin',
          max: 'dataMax',
          // boundaryGap:['5%','5%']
      },
      yAxis: {
          scale: true,
          splitArea: {
              show: true
          },
          boundaryGap:['10%','10%']
      },
      dataZoom: [
          {
              type: 'inside',
              start: 50,
              end: 100
          },
          {
              show: true,
              type: 'slider',
              y: '90%',
              start: 50,
              end: 100
          }
      ],
      series: [
          {
              name: '分时图',
              type: 'line',
              data: calculate(data,1),
              smooth: true,
              lineStyle: {
                  normal: {
                    width:1,
                  }
              }
          },
          {
              name: '1分钟K线图',
              type: 'candlestick',
              hoverAnimation:false,
              itemStyle:{
                normal:{
                  borderWidth:0.5,
                },
                emphasis:{
                  borderWidth:0.5,
                }
              },
              data: data.values,
              show : true,
          }
      ]
  };
  myChart.setOption(option);

  myChart.on('legendselectchanged', function (params) {
      if(params.name=='分时图'){
          myChart.hideLoading();
          option.legend.selected['分时图'] = true;
          option.legend.selected['1分钟K线图'] = false;
          myChart.setOption(option);
      }else if(params.name=='1分钟K线图'){
          myChart.hideLoading();
          option.legend.selected['分时图'] = false;
          option.legend.selected['1分钟K线图'] = true;
          myChart.setOption(option);
      }
  });
}



function splitData(rawData) {
    var categoryData = [];
    var values = []
    for (var i = 0; i < rawData.length; i++) {
        categoryData.push(rawData[i].splice(0, 1)[0]);
        values.push(rawData[i])
    }
    return {
        categoryData: categoryData,
        values: values
    };
}

function calculate(data0,dayCount) {
    var result = [];
    for (var i = 0, len = data0.values.length; i < len; i++) {
        if (i < dayCount) {
            result.push('-');
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += data0.values[i - j][1];
        }
        result.push(sum / dayCount);
    }
    return result;
}






</script>

<?php $this->load->view('common/wx_share.php');?>


</body>
</html>
